﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Linq.Expressions;
using System.Data.Common;

namespace CH.Easy.DbProvider.Core
{
    public class DbQueryEnumerator<T> : IEnumerator<T>, IEnumerator, IDisposable
    {
        private DbDataReader reader;
        private Delegate de;
        private T current;
        public DbQueryEnumerator(DbDataReader reader,LambdaExpression resultExpression)
        {
            this.reader = reader;
            this.de = resultExpression.Compile();
        }
        public T Current
        {
            get { return current; }
        }

        public void Dispose()
        {
            this.reader.Close();
            this.reader.Dispose();
        }

        object IEnumerator.Current
        {
            get { return this.current; }
        }

        public bool MoveNext()
        {
            if (this.reader.Read())
            {
                current = (T)de.DynamicInvoke(this.reader);
                return true;
            }
            else 
            {
                return false;
            }
        }

        public void Reset()
        {
            
        }
    }
}
